<template>
  <div class="register">
    <van-nav-bar title="注册">
      <template #left>
        <router-link to="/">首页</router-link>
      </template>
      <template #right>
        <router-link to="/login">登录</router-link>
      </template>
    </van-nav-bar>

    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="passwordState"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="请再次确认密码"
        :rules="[{ required: true }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  data() {
    return {
      username: "",
      password: "",
      passwordState: "",
    };
  },
  methods: {
    // 定义方法，验证确认密码
    checkRepwd(){
      let reg = /^\d{6}$/;
      //  验证正则表达式             逻辑与        判断两次输入的密码是否一致
      if(reg.test(this.passwordState) && this.password==this.passwordState){ // 同时满足则验证成功
        return true;
      }else{ // 验证失败

        return false;
      }
    },
    // 定义方法，验证密码
    checkPwd(){
      let reg = /^\d{6}$/;
      //  验证正则表达式
      if(reg.test(this.password)){ // 验证成功
        return true;
      }else{ // 验证失败
        return false;
      }
    },

    // 定义方法，验证用户名
    checkUsername(){
      // 验证用户名  要求单词字符6~15位 [A-Za-z0-9_]
      let reg = /^\w{6,15}$/;
      if(reg.test(this.username)){ // 验证成功
        return true;
      }else{ // 验证失败
        return false;
      }
    },

    // 点击注册之后执行，验证表单
    onSubmit(){
      // 三个函数方法同时满足了,就提交表单申请
      if (this.checkUsername() & this.checkPwd() & this.checkRepwd()){
         this.axios
        .post(
          "/register",
          `username=${this.username}&password=${this.password}`
        )
        .then((result) => {
          console.log(result);
          // 接收数据库返回的验证结果
          if (result.data.code == 200) {
            Toast.success("注册成功");
            this.$router.push("/login");
          } else if (result.data.code == 201) {
            Toast.fail("注册失败");
          }
        });
      }
    },
  },
};
</script>

<style>
.register .van-nav-bar {
  /* 统一主色调 */
  background-color: #1989FA;
}
.register .van-nav-bar__title,
.register .van-nav-bar__left a,
.register .van-nav-bar__right a {
  color: white;
}
.register .van-button {
  border: 0;
}
</style>